package com.king.nio.filechannel;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * ByteBuffer文件写出案例
 *
 * @author king
 * @date 2020/12/26 22:53
 */
public class NioFileChannel01 {
    public static void main(String[] args) throws IOException {
        String str = "hello";

        // 创建一个输出流 -> channel
        FileOutputStream fileOutputStream = new FileOutputStream("e:/NioFileChannel01.txt");

        // 通过 fileOutputStream 获取对应的 FileChannel
        // fileChannel 的真实类型是 FileChannelImpl
        FileChannel fileChannel = fileOutputStream.getChannel();

        // 创建一个缓冲区 ByteBuffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        // 将 str 放入 byteBuffer
        byteBuffer.put(str.getBytes());

        // 对 byteBuffer 进行 flip
        byteBuffer.flip();

        // 将 byteBuffer 数据写入到 fileChannel
        fileChannel.write(byteBuffer);
        fileOutputStream.close();
    }
}
